<?php

// +----------------------------------------------------------------------
// |ZBPHP[基于ThinkPHP5.1开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2016-2019 http://www.benbenwangluo.com
// +----------------------------------------------------------------------
// | Author 似水星辰 [ 2630481389@qq.com ]
// +----------------------------------------------------------------------
// | 中犇软件 技术六部 出品
// +----------------------------------------------------------------------

namespace app\api\controller\v1;

use app\api\controller\Base;
use app\common\model\Order as OrderModel;
use app\order\model\OrderRefund;
use service\ApiReturn;
use think\Db;

/**
 * 售后部分
 * @author 晓风<215628355@qq.com>
 * @date 2021-11-4 16:00:19
 */
class Refund extends Base
{


    /**
     * 退单申请
     * @param $data
     * @param $user
     * @author 晓风 2021-08-07重构
     */
    public function refund_apply($data, $user)
    {
        // order_status = 4 => 5
        $order_sn = $data['order_sn'];
        $order = OrderModel::where('order_sn', $order_sn)->where("order_type", "in", [3, 6])->where("user_id", $user["id"])->find();
        if (!$order) {
            return ApiReturn::r(0, '', '此订单不支持退款');
        }
       //加进程锁
        $locKey = "lock_refund_" . $order["order_sn"];
        $redis = \app\common\model\Redis::handler();
        $lock = $redis->get($locKey);
        if ($lock) {
            throw new \Exception('操作过快，请稍等');
        }
        $redis->setnx($locKey, 1);
        Db::startTrans();
        try {
            $data["sku_id"] = $data["sku_id"] ?? 0;
            OrderRefund::refundApply($order, $data);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return ApiReturn::r(0, '' . $e->getMessage());
        }
        catch (\Error $e) {
            Db::rollback();
            return ApiReturn::r(0, '' . $e->getMessage());
        }
         //无论是否抛出异常，此处代码会保活
        finally{
           $redis->del($locKey);
        }
        return ApiReturn::r(1, '', '申请成功');
    }


    /**
     * 取消订单
     * @param $data
     * @param $user
     */
    public function cancel_order($data, $user)
    {
        try {
            $map[] = ["order_sn", "=", $data["order_sn"]];
            $map[] = ["status", "=", 0];
            $map[] = ["order_type", "in", [3, 6]];
            $map[] = ["user_id", "=", $user["id"]];

            $order = OrderModel::where($map)->find();
            if (!$order) {
                throw new \Exception('订单不可操作，请刷新');
            }
            $return_id = $data['return_id'] ?: 0;
            \app\order\model\OrderGoods::cancelOrderUser($order,$return_id);
        } catch (\Exception $e) {
            return ApiReturn::r(0, '', $e->getMessage());
        }
        return ApiReturn::r(1, '', '取消成功');
    }


    /**
     * 售后list
     * @param $data
     * @param $user
     */
    public function refund_list($data, $user)
    {
        $map[] = ['order_refund.user_id', '=', $user['id']];
        $map[] = ['order_refund.is_delete', '=', 0];
        if ($data['type']) {
            switch ($data['type']) {
                case 'apply':
                    $map[] = ['order_refund.status', '=', 0];

                    break;
                case 'deal':
                    $map[] = ['order_refund.status', 'in', [1, 2]];

                case 'success':
                    $map[] = ['order_refund.status', 'in', [3]];

                    break;
            }
        }
        $order = "order_refund.id desc";
        $size = $data["size"] ?: 15;
        $list = OrderRefund::getList($map, $order, $size);
        $info = [];
        foreach ($list as $item) {
            $item['status_title'] = OrderRefund::$status[$item['status']];
            $item['refund_type_title'] = OrderRefund::$refundGoodsState[$item['refund_type']];
            $item['order_type_title'] = OrderModel::$orderTypes[$item['order_type']];
            $item['goods_thumb'] = get_thumb($item['goods_thumb']);
            $info[] = $item;// $this->filter($item);
        }
        return ApiReturn::r(1, $this->getThinkPage($list, $info), '请求成功');
    }


    /**
     *获取发货人的退货地址
     * @param {*} $data
     * @param {*} $user
     * @return {*}
     * @Date: 2021-05-07 10:30:57
     */
    public function refund_sender($data, $user)
    {
        $order_refund = Db::name('order_refund')
            ->where(['id' => $data['id']])
            ->find();
        //$goods = Db::name('goods')->get($order_refund['goods_id']);
        $sender_id = Db::name('order')->where('order_sn', $order_refund['order_sn'])->value('sender_id');
        $sender = Db::name('goods_express_sender')->get($sender_id);
        return ApiReturn::r(1, ['sender' => $sender], lang('请求成功'));
    }

    /**
     * 退单取消
     * @param $data
     * @param $user
     */
    public function refund_cancel($data, $user)
    {

        Db::startTrans();
        try {
            OrderRefund::cancelOrder($data['id'], $user["id"], -2);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return ApiReturn::r(0, '' . $e->getMessage());
        }
        return ApiReturn::r(1, '', '申请成功');
    }


    /**
     * 售后详情
     * @param $data
     * @param $user
     */
    public function refund_detaile($data, $user)
    {

        $item = OrderRefund::getInfo($data['id']);
        if (!$item) {
            return ApiReturn::r(0, [], '未找到售后申请');
        }

        $item['status_title'] = OrderRefund::$status[$item['status']];
        $item['refund_type_title'] = OrderRefund::$refundGoodsState[$item['refund_type']];
        $item['refund_pay_type_title'] = $item['status'] == 3 ? (OrderModel::$payTypes[$item['refund_pay_type']] ?? "其他渠道") : "预计原路退回";
        $item['order_type_title'] = OrderModel::$orderTypes[$item['order_type']];
        $item['goods_thumb'] = get_thumb($item['goods_thumb']);
        $item['head_img'] = get_thumb($item['head_img']);
        $item['refund_picture'] = get_files_url($item['refund_picture']);

        $item['refund_time'] = format_time($item['refund_time']);
        $item['cancel_time'] = format_time($item['cancel_time']);
        return ApiReturn::r(1, $item, '请求成功');
    }

    /**
     * 售后物流信息填写(用户退货填写寄回物流信息)
     * @param $data
     * @param $user
     */
    public function refund_express($data, $user)
    {
        $res = $this->validate($data, \app\order\validate\RefundExpress::class);
        if (true !== $res) {
            return ApiReturn::r(0, '', $res);
        }
        $order_refund = OrderRefund::where("id", $data["id"])->where("user_id", $user["id"])->find();
        if (!$order_refund) {
            return ApiReturn::r(0, '', '未找到售后单');
        }
        if ($order_refund["status"] != 1) {
            return ApiReturn::r(0, '', '订单未审核');
        }
        $express_company = \app\order\model\ExpressCompany::where("aid", $data['express_company_id'])->field("name,logo,tel,express_no")->find();
        if (!$express_company) {
            return ApiReturn::r(1, '', '物流公司选择错误');
        }
        $res = OrderRefund::where(['id' => $order_refund['id']])->update([
            'express_no' => $data['express_no'],
            'express_company_id' => $data['express_company_id'],
            "shipping_time"=> time()
        ]);
        if (!$res) {
            return ApiReturn::r(0, '', '保存物流信息失败');
        }
        return ApiReturn::r(1, '', '已保存物流信息');

    }
    
    /**
     * 售后删除
     * @param $data
     * @param $user
     */
    public function del_refound($data, $user){
        
        $info = OrderRefund::where(['id' => $data['id']])->where("user_id",$user["id"])->find();
        if (!$info) {
            return ApiReturn::r(0, [], '未找到该订单');
        }
        if($info["status"] < 0){
           OrderRefund::where(['id' => $info['id']])->delete();         
        } 
        else if($info["status"] == 3){
           OrderRefund::where(['id' => $info['id']])->setField("is_delete",1);         
        } else{
            return ApiReturn::r(0, [], '暂不可删除');
        }     
        return ApiReturn::r(1, [], '已删除');
    }

    /**
     * 获取可退款金额
     * @param $data
     * @param $user
     */
    public function get_refund_money($data, $user)
    {
        $order_sn = $data['order_sn'];
        $order = OrderModel::where('order_sn', $order_sn)->where("order_type", "in", [3, 6])->find();
        if (!$order) {
            return ApiReturn::r(0, '', '此订单不支持退款');
        }
        Db::startTrans();
        try {
            $data["sku_id"] = $data["sku_id"] ?? 0;
            $goods = OrderRefund::getRefundMoney($order, $data);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return ApiReturn::r(0, '' . $e->getMessage());
        }
        $goods["goods_thumb"] = get_thumb($goods["goods_thumb"]);
        $goods['refund_reason'] =  Db::name('order_refund_reason')->field("id,reason")->where(['status' => 1, 'type' =>  1])->select();
        return ApiReturn::r(1, $goods, '查询成功');
    }


    public function refund_update($data, $user)
    {
        return ApiReturn::r(0, [], lang('根据政策，暂不支持修改'));
    }

    /**
     * 获取退换货原因/取消原因
     */
    public function refundReason($data = [], $user = [])
    {
        $list = Db::name('order_refund_reason')->field("id,reason")->where(['status' => 1, 'type' => $data['type']])->select();
        return ApiReturn::r(1, $list, lang('查询成功'));
    }
}
